package com.mntp.handler.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;


import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

@Slf4j
public class ServerInboundHandler1 extends ChannelInboundHandlerAdapter {

    /**
     * 通道准备就绪
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("ServerInboundHandler1 channelActive");
        super.channelActive(ctx);
    }



    /**
     * 从通道读到了数据
     * 1. 数据比较少，直接发送的时候，这里只会调用一次
     * 2. 数据比较大，分批发送的时候，这里会调用多次
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("ServerInboundHandler1 channelRead---------");
        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        String message = new String(bytes, Charset.defaultCharset());
        log.info("ServerInboundHandler1 channelRead 收到客户端消息："+message);
        super.channelRead(ctx, msg);
    }

    /**
     *通道内数据已读取完毕
     *
     * 1.数据比较少，直接发送的时候，这里只会调用一次
     * 2.数据比较大，分批发送的时候，这里只会调用一次
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("ServerInboundHandler1 channelReadComplete---------");
        //给客户端回写数据方便测试
        Channel channel = ctx.channel();
        ByteBuf buffer = ctx.alloc().buffer();
        buffer.writeBytes("hello netty client, i am netty server \n".getBytes(StandardCharsets.UTF_8));
        channel.writeAndFlush(buffer);
        super.channelReadComplete(ctx);
    }

    /**
     * 读数据异常的回调
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("ServerInboundHandler1 exceptionCaught---------");
        super.exceptionCaught(ctx, cause);
    }
}
